package za.ac.sun.cs.viz.distrib;

import java.util.Arrays;

public class VizTreeNode {

	private final String name;

	private VizTreeNode leftChild = null;

	private VizTreeNode rightChild = null;

	private VizTreeNodeVersion[] versions;
	
	private VizTreeNodeVersion dummy = new VizTreeNodeVersion(0, 0, 0, null, 0);

	private int versionCount;

	public VizTreeNode(String name) {
		this.name = name;
		versions = new VizTreeNodeVersion[2];
		versionCount = 0;
	}

	public void addValue(long timestamp, int id, long value, int activity) {
		if (versionCount == versions.length) {
			versions = Arrays.copyOf(versions, versions.length * 2);
		}
		versions[versionCount++] = new VizTreeNodeVersion(timestamp, id, value, name, activity);
	}

	public long getValue(long timestamp) {
		dummy.setTimestamp(timestamp);
		int i = Arrays.binarySearch(versions, 0, versionCount, dummy);
		if (i >= 0) {
			return versions[i].getValue();
		} else if (i < -1) {
			return versions[-(i + 2)].getValue();
		} else {
			return 0;
		}
	}

	public VizNode getVizNode(long timestamp) {
		dummy.setTimestamp(timestamp);
		if (versionCount == 0) {
			System.out.println("PROBLEM");
		}
		int i = Arrays.binarySearch(versions, 0, versionCount, dummy);
		if (i >= 0) {
			return versions[i].getVizNode(true);
		} else if (i < -1) {
			return versions[-(i + 2)].getVizNode(false);
		} else {
			return null;
		}
	}
	
	public void addChild(VizTreeNode child) {
		if (leftChild == null) {
			leftChild = child;
		} else if (child != leftChild) {
			rightChild = child;
		}
	}

	public VizTreeNode getLeftChild() {
		return leftChild;
	}

	public VizTreeNode getRightChild() {
		return rightChild;
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("name == ").append(name);
		sb.append("\nversionCount == ").append(versionCount);
		for (int i = 0; i < versionCount; i++) {
			sb.append("\n  ").append(versions[i].getTimeStamp());
			sb.append(' ').append(versions[i].getValue());
		}
		return sb.toString();
	}
	
}
